package com.lagou.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description:
 * @author: yx
 * @date: 2021/11/2 10:45
 */
public class ServerDemo {

    public static void main(String[] args) throws Exception {
        //1. 创建连接池,如果有客户端连接就创建一个线程,进行通信
        ExecutorService executorService = Executors.newCachedThreadPool();
        //2. 创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务端启动成功");
        while (true) {
            //3. 监听客户端
            Socket socket = serverSocket.accept();
            System.out.println("有客户端连接===");

            //4. 开启新的线程处理
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    handleSocket(socket);
                }
            });
        }
    }

    private static void handleSocket(Socket socket) {
        System.out.println("线程id: " + Thread.currentThread().getId() +
                "线程名称: " + Thread.currentThread().getName());
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);
            System.out.println("客户端: " + new String(bytes, 0 , read));
            OutputStream outputStream = socket.getOutputStream();
            System.out.print("我: ");
            Scanner scanner = new Scanner(System.in);
            String msg = scanner.nextLine();
            outputStream.write(msg.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
